package com.xbongbong.crm.perform.query.detail;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmDetailTopInfoService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.AddressEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.parent.help.CommonPermissionHelp;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.model.PaasCommentModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.service.BusinessButtonService;
import com.xbongbong.paas.service.DetailTabConfigService;
import com.xbongbong.paas.service.LinkListService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.parent.util.CommonBusinessFieldUtil;
import com.xbongbong.parent.util.DataUtil;
import com.xbongbong.pro.appdetail.pojo.MobileDetailMoneyItemPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailScriptPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusPojo;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.CustomerCommunicateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.BusinessCommentEnum;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.CommunicateBaseEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.LikeModel;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.NameUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;

/**
 * @author sunshaoxiang
 * @ClassName CustomerCommunicateDetailTopInfoServiceImpl
 * @Description 跟进记录详情页 上部信息业务层
 * @Date 2022/6/6 14:54
 * @Version 1.0
 **/
@Service("customerCommunicateDetailTopInfoServiceImpl")
public class CustomerCommunicateDetailTopInfoServiceImpl extends AbstractCrmDetailTopInfoService {

    public static final Logger LOGGER = LoggerFactory.getLogger(CustomerCommunicateDetailTopInfoServiceImpl.class);

    @Resource
    private PaasMenuModel paasMenuModel;

    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private PaasCommentModel paasCommentModel;
    @Resource
    private LikeModel likeModel;
    @Resource
    private LinkListService linkListService;
    @Resource
    private DetailTabConfigService detailTabConfigService;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private CommonPermissionHelp commonPermissionHelp;
    @Resource
    private BusinessButtonService businessButtonService;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private ClueModel clueModel;
    @Resource
    private UserModel userModel;
    @Resource
    private CustomerUserModel customerUserModel;


    @Override
    public List<Integer> businessType() {
        return Collections.singletonList(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode());
    }

    @Override
    public List<SummaryDataPoJo> getSummaryList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        JSONArray summaryAttrArray = CommonBusinessFieldUtil.getShowAttrList(formDataDetailDTO.getBusinessType());
        List<SummaryDataPoJo> summaryDataList = ExplainUtil.getSummaryDataList(summaryAttrArray, paasFormDataEntityExt.getData(), explainMap, paasFormDataEntityExt);
        handleSummarySpecialAttr(summaryDataList, data, paasFormDataEntityExt);
        return summaryDataList;
    }

    /**
     * 处理summaryList中需要特殊处理的字段
     * 重构前 -> com.xbongbong.saas.service.impl.MobileDetailServiceImpl#handleSummarySpecialAttr(java.lang.String, java.util.List, java.lang.Integer, com.alibaba.fastjson.JSONObject, java.lang.Long, com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt)
     * @param summaryList
     * @param data
     * @param paasFormDataEntityExt
     * @throws XbbException
     */
    private void handleSummarySpecialAttr(List<SummaryDataPoJo> summaryList, JSONObject data, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        SummaryDataPoJo communicateImageSummary = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.IMAGES.getAttr());
        if (Objects.nonNull(communicateImageSummary)) {
            JSONArray imageArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, CustomerCommunicateEnum.IMAGES.getAttr(), new JSONArray());
            communicateImageSummary.setValue(imageArray);
            communicateImageSummary.setImageExtra();
        }
        String communicateUserName = "";
        SummaryDataPoJo userSummary = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.USER_NAME.getAttr());
        if (Objects.isNull(userSummary) && Objects.nonNull(paasFormDataEntityExt)) {
            communicateUserName = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_NAME.getAttr(), "");
            SummaryDataPoJo userNameSummary = new SummaryDataPoJo();
            userNameSummary.setAttr(CustomerCommunicateEnum.USER_NAME.getAttr());
            userNameSummary.setSaasAttr(CustomerCommunicateEnum.USER_NAME.getSaasAttr());
            userNameSummary.setAttrName(CustomerCommunicateEnum.USER_NAME.getAttrName());
            userNameSummary.setValue(Collections.singletonList(communicateUserName));

            //老数据存的string,现在变成list,故进行判断
            SummaryDataPoJo userAvatarSummary = new SummaryDataPoJo();
            if (data.containsKey(CustomerCommunicateEnum.USER_AVATAR.getAttr())) {
                Object object = data.get(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                if (object != null) {
                    if (object instanceof String) {
                        String userAvatar = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_AVATAR.getAttr(), "");
                        userAvatarSummary.setAttr(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                        userAvatarSummary.setSaasAttr(CustomerCommunicateEnum.USER_AVATAR.getSaasAttr());
                        userAvatarSummary.setAttrName(CustomerCommunicateEnum.USER_AVATAR.getAttrName());
                        userAvatarSummary.setValue(Collections.singletonList(userAvatar));
                    } else {
                        List<Object> userAvatar = DataUtil.getListFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_AVATAR.getAttr());
                        userAvatarSummary.setAttr(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                        userAvatarSummary.setSaasAttr(CustomerCommunicateEnum.USER_AVATAR.getSaasAttr());
                        userAvatarSummary.setAttrName(CustomerCommunicateEnum.USER_AVATAR.getAttrName());
                        userAvatarSummary.setValue(userAvatar);
                    }
                }
            }

            summaryList.add(0, userNameSummary);
            summaryList.add(0, userAvatarSummary);
        }

        SummaryDataPoJo communicateTime = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr());
        if (Objects.nonNull(communicateTime)) {
            Long crmCommunicateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr(), 0L);
            if (!Objects.equals(crmCommunicateTime, 0L)) {
                communicateTime.setValue(Collections.singletonList(DateTimeUtil.getStringEpochSecond(crmCommunicateTime, DateTimeUtil.SDFMDHM)));
            }
        }
        SummaryDataPoJo communicateContact = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr());
        if (Objects.nonNull(communicateContact)) {
            JSONArray contactArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, CustomerCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr(), new JSONArray());
            if (contactArr != null && !contactArr.isEmpty()) {
                StringBuilder name = new StringBuilder();
                for (int i = 0; i < contactArr.size(); i++) {
                    String contact = contactArr.getString(i);
                    name.append(contact).append("、");
                }
                // 去掉最后的"、"号
                String subStringName = name.toString().substring(0, name.length() - 1);
                communicateContact.setValue(Collections.singletonList(subStringName));
            }
        }
        SummaryDataPoJo customerNamePojo = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
        SummaryDataPoJo communicateAddress = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.ADDRESS.getAttr());
        if (Objects.nonNull(communicateAddress)) {
            List<Object> values = communicateAddress.getValue();
            if (Objects.nonNull(values) && !values.isEmpty() && Objects.nonNull(values.get(0))) {
                JSONObject addressObj = (JSONObject) values.get(0);
                String province = addressObj.getString(AddressEnum.PROVINCE.getAlias());
                String city = addressObj.getString(AddressEnum.CITY.getAlias());
                String district = addressObj.getString(AddressEnum.DISTRICT.getAlias());
                String address = addressObj.getString(AddressEnum.ADDRESS.getAlias());
                StringBuilder detailAddress = new StringBuilder();
                detailAddress.append(province).append(city).append(district).append(address);
                communicateAddress.setValue(Collections.singletonList(detailAddress));

                JSONObject locationJsonObj = addressObj.getJSONObject("location");
                Double lon = 0D;
                Double lat = 0D;
                if (locationJsonObj != null) {
                    lon = locationJsonObj.getDouble("lon");
                    lat = locationJsonObj.getDouble("lat");
                }
                String customerName = "";
                if (Objects.nonNull(customerNamePojo)) {
                    List<Object> customerNameValues = customerNamePojo.getValue();
                    if (Objects.nonNull(customerNameValues) && !customerNameValues.isEmpty()) {
                        customerName = (String) customerNameValues.get(0);
                    }
                }
                String title = communicateUserName + I18nMessageUtil.getMessage(I18nStringConstant.FOLLOW_UP_CUSTOMERS) + customerName;
                communicateAddress.setAddressExtra(lat, lon, title);
            }
        }
    }

    @Override
    public List<SummaryDataPoJo> getLabelList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        // 解析标签
        return ExplainUtil.getSpecialSummaryList(formEntity.getLabelsList(), data, explainMap, formData);
    }

    @Override
    public List<FormTitlePoJo> getTitleList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        return ExplainUtil.getSpecailFormTitle(JSONArray.parseArray(formEntity.getCustomTitle()), explainMap, data, list, formData);
    }

    @Override
    public List<MobileDetailMoneyItemPojo> getMobileDetailMoneyInfo(Integer distributorMark, String corpid, String userId, Integer businessType, Integer subBusinessType, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        return new ArrayList<>();
    }

    @Override
    public JSONArray getBottomBlockInfo(String corpid, String userId, Integer businessType, PaasFormEntityExt formEntity, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt entityExt, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        return new JSONArray();
    }

    @Override
    public List<MobileDetailScriptPojo> getDetailShowScript(Integer businessType, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        return new ArrayList<>();
    }

    @Override
    public MobileDetailStatusPojo getDetailShowStatus(Integer businessType, JSONObject data) throws XbbException {
        return null;
    }

    @Override
    public Map<String, Object> getDetailShowOperation(String corpid, String userId, Integer businessType, Long dataId, JSONObject data) throws XbbException {
        return new HashMap<>(BasicConstant.DEFAULT_ACCURACY);
    }

    @Override
    public JSONObject returnSaasObject(String corpid, Integer businessType, UserVO userVO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        return null;
    }

    @Override
    public List<TopPermissionsPoJo> dingtalkHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        String corpid = formEntity.getCorpid();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer businessType = formEntity.getBusinessType();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, userVO.getPermSet());
        List<String> aliasIn = new ArrayList<>();
        workFlowEnumList.forEach(item -> aliasIn.add(XbbRefTypeEnum.getByCode(item.getBusinessType()).getAlias()));
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);

        List<TopPermissionsPoJo> topPermissions = businessButtonService.dingtalkDetailCommon(userVO, formEntity, explainMap, formData);
        List<LinkListPojo> linkList = formEntity.getLinkListList();
        topPermissions.addAll(linkListService.getDingtalkCommonButton(linkList, formData.getDel(), userVO, formData.getAppId(), formData.getFormId(), businessType, formEntity.getSaasMark(), corpid));

        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
            BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
            if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                NameUtil.changeValue(paasBusinessTypeToName, topPermissionsPoJo);
            }
            topPermissionsPoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(workFlowEnum.getBusinessType()));
            topPermissionsPoJo.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
            topPermissions.add(topPermissionsPoJo);
        }
        return topPermissions;
    }

    @Override
    public void returnVO(PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, MobileFormCommonDetailVO mobileFormCommonDetailVO, String userId) throws XbbException {
        mobileFormCommonDetailVO.setHasOuterLinkShare(setOuterLinkShare(formEntity.getCorpid(), formEntity.getId()));
        mobileFormCommonDetailVO.setDistributorMark(formEntity.getDistributorMark());
        mobileFormCommonDetailVO.setPaasFormEntity(formEntity);
    }


    @Override
    public List<WorkFlowPojo> webHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Set<String> permSet = userVO.getPermSet();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermission(businessType, permSet);
        List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
        String corpid = userVO.getCorpid();
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 获取对应businessType的alias
        List<String> aliasIn = new ArrayList<>();
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            if (Objects.isNull(workFlowEnum.getBusinessType())) {
                continue;
            }
            aliasIn.add(XbbRefTypeEnum.getByCode(workFlowEnum.getBusinessType()).getAlias());
        }
        param.put("corpid", corpid);
        param.put("aliasIn", aliasIn);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        List<PaasMenuEntity> paasMenuEntities = paasMenuModel.findEntitys(param);
        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasMenuEntities.forEach(item-> paasBusinessTypeToName.put(XbbRefTypeEnum.getByAlias(item.getAlias()).getCode(),item.getName()));
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            WorkFlowPojo workFlowPojo = new WorkFlowPojo();
            BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
            NameUtil.changeValue(paasBusinessTypeToName, workFlowPojo);
            workFlowPojoList.add(workFlowPojo);
        }
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        workFlowPojoList.addAll(linkListService.getCommonButton(linkList, formData.getDel(), handelDetailPojo.getLoginUser(), formData.getAppId(), formData.getFormId(), handelDetailPojo.getBusinessType(), SaasMarkEnum.SAAS.getCode(), corpid));
        return workFlowPojoList;
    }

    @Override
    public void handleDetailSpecialField(PaasFormDataEntityExt formData, JSONObject data, Map<String, FieldAttrEntity> explainMap, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        Integer crmBusinessType = getIntegerOrDefaultFromFormData(data, CommunicateBaseEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), BasicConstant.ZERO);
        if (!Objects.equals(crmBusinessType, BasicConstant.ZERO)) {
            String businessName = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr(), "");
            if (!businessName.isEmpty()) {
                businessName = RedundantTemplateTypeEnum.getByCode(crmBusinessType).getName() + PaasConstant.LEFT_BRACKET + businessName + PaasConstant.RIGHT_BRACKET;
                data.put(CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr(), businessName);
            }
        }
    }

    @Override
    public JSONArray getSecondTitleList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formDataDetailDTO.getBusinessType();
        Long dataId = paasFormDataEntityExt.getId();
        JSONArray summaryAttrArray = CommonBusinessFieldUtil.getShowAttrList(formDataDetailDTO.getBusinessType());
        List<SummaryDataPoJo> summaryList = ExplainUtil.getSummaryDataList(summaryAttrArray, paasFormDataEntityExt.getData(), explainMap, paasFormDataEntityExt);
        handleSummarySpecialAttr(corpid, summaryList, businessType, data, dataId, paasFormDataEntityExt);
        JSONArray secondTitle = getSecondTitleList(summaryList, data, formDataDetailDTO.getCorpid(), formEntity.getId());
        return secondTitle;
    }

    /**
     * 处理summaryList中需要特殊处理的字段
     * 重构前 -> com.xbongbong.saas.service.impl.MobileDetailServiceImpl#handleSummarySpecialAttr(java.lang.String, java.util.List, java.lang.Integer, com.alibaba.fastjson.JSONObject, java.lang.Long, com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt)
     * @param corpid
     * @param summaryList
     * @param businessType
     * @param data
     * @param dataId
     * @param paasFormDataEntityExt
     */
    private void handleSummarySpecialAttr(String corpid, List<SummaryDataPoJo> summaryList, Integer businessType, JSONObject data, Long dataId, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        SummaryDataPoJo communicateImageSummary = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.IMAGES.getAttr());
        if (Objects.nonNull(communicateImageSummary)) {
            JSONArray imageArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, CustomerCommunicateEnum.IMAGES.getAttr(), new JSONArray());
            communicateImageSummary.setValue(imageArray);
            communicateImageSummary.setImageExtra();
        }
        String communicateUserName = "";
        SummaryDataPoJo userSummary = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.USER_NAME.getAttr());
        if (Objects.isNull(userSummary) && Objects.nonNull(paasFormDataEntityExt)) {
            communicateUserName = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_NAME.getAttr(), "");
            SummaryDataPoJo userNameSummary = new SummaryDataPoJo();
            userNameSummary.setAttr(CustomerCommunicateEnum.USER_NAME.getAttr());
            userNameSummary.setSaasAttr(CustomerCommunicateEnum.USER_NAME.getSaasAttr());
            userNameSummary.setAttrName(CustomerCommunicateEnum.USER_NAME.getAttrName());
            userNameSummary.setValue(Collections.singletonList(communicateUserName));

            //老数据存的string,现在变成list,故进行判断
            SummaryDataPoJo userAvatarSummary = new SummaryDataPoJo();
            if (data.containsKey(CustomerCommunicateEnum.USER_AVATAR.getAttr())) {
                Object object = data.get(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                if (object != null) {
                    if (object instanceof String) {
                        String userAvatar = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_AVATAR.getAttr(), "");
                        userAvatarSummary.setAttr(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                        userAvatarSummary.setSaasAttr(CustomerCommunicateEnum.USER_AVATAR.getSaasAttr());
                        userAvatarSummary.setAttrName(CustomerCommunicateEnum.USER_AVATAR.getAttrName());
                        userAvatarSummary.setValue(Collections.singletonList(userAvatar));
                    } else {
                        List<Object> userAvatar = FormDataUtil.getListFromFormData(paasFormDataEntityExt.getData(), CustomerCommunicateEnum.USER_AVATAR.getAttr());
                        userAvatarSummary.setAttr(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                        userAvatarSummary.setSaasAttr(CustomerCommunicateEnum.USER_AVATAR.getSaasAttr());
                        userAvatarSummary.setAttrName(CustomerCommunicateEnum.USER_AVATAR.getAttrName());
                        userAvatarSummary.setValue(userAvatar);
                    }
                }
            }

            summaryList.add(0, userNameSummary);
            summaryList.add(0, userAvatarSummary);
        }

        SummaryDataPoJo communicateTime = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr());
        if (Objects.nonNull(communicateTime)) {
            Long crmCommunicateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr(), 0L);
            if (!Objects.equals(crmCommunicateTime, 0L)) {
                communicateTime.setValue(Collections.singletonList(DateTimeUtil.getStringEpochSecond(crmCommunicateTime, DateTimeUtil.SDFMDHM)));
            }
        }
        SummaryDataPoJo communicateContact = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr());
        if (Objects.nonNull(communicateContact)) {
            JSONArray contactArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, CustomerCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr(), new JSONArray());
            if (contactArr != null && !contactArr.isEmpty()) {
                StringBuilder name = new StringBuilder();
                for (int i = 0; i < contactArr.size(); i++) {
                    String contact = contactArr.getString(i);
                    name.append(contact).append("、");
                }
                // 去掉最后的"、"号
                String subStringName = name.toString().substring(0, name.length() - 1);
                communicateContact.setValue(Collections.singletonList(subStringName));
            }
        }
        SummaryDataPoJo customerNamePojo = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
        SummaryDataPoJo communicateAddress = getSummaryDataPoJoByAttr(summaryList, CustomerCommunicateEnum.ADDRESS.getAttr());
        if (Objects.nonNull(communicateAddress)) {
            List<Object> values = communicateAddress.getValue();
            if (Objects.nonNull(values) && !values.isEmpty() && Objects.nonNull(values.get(0))) {
                JSONObject addressObj = (JSONObject) values.get(0);
                String province = addressObj.getString(AddressEnum.PROVINCE.getAlias());
                String city = addressObj.getString(AddressEnum.CITY.getAlias());
                String district = addressObj.getString(AddressEnum.DISTRICT.getAlias());
                String address = addressObj.getString(AddressEnum.ADDRESS.getAlias());
                StringBuilder detailAddress = new StringBuilder();
                detailAddress.append(province).append(city).append(district).append(address);
                communicateAddress.setValue(Collections.singletonList(detailAddress));

                JSONObject locationJsonObj = addressObj.getJSONObject("location");
                Double lon = 0D;
                Double lat = 0D;
                if (locationJsonObj != null) {
                    lon = locationJsonObj.getDouble("lon");
                    lat = locationJsonObj.getDouble("lat");
                }
                String customerName = "";
                if (Objects.nonNull(customerNamePojo)) {
                    List<Object> customerNameValues = customerNamePojo.getValue();
                    if (Objects.nonNull(customerNameValues) && !customerNameValues.isEmpty()) {
                        customerName = (String) customerNameValues.get(0);
                    }
                }
                String title = communicateUserName + I18nMessageUtil.getMessage(I18nStringConstant.FOLLOW_UP_CUSTOMERS) + customerName;
                communicateAddress.setAddressExtra(lat, lon, title);
            }
        }
    }

    /**
     * 通过摘要字段获取摘要内容
     * 重构前 -> com.xbongbong.saas.service.impl.MobileDetailServiceImpl#getSummaryDataPoJoByAttr(java.util.List, java.lang.String)
     * @param summaryList
     * @param attr
     * @return
     */
    private SummaryDataPoJo getSummaryDataPoJoByAttr(List<SummaryDataPoJo> summaryList, String attr) {
        for (SummaryDataPoJo summaryItem : summaryList) {
            if (Objects.equals(summaryItem.getAttr(), attr)) {
                return summaryItem;
            }
        }
        return null;
    }

    @Override
    public JSONArray getTagList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formEntity.getBusinessType();
        Long dataId = paasFormDataEntityExt.getId();
        String userId = formDataDetailDTO.getUserId();
        Long formId = paasFormDataEntityExt.getFormId();
        List<SummaryDataPoJo> labelsList = getLabelList(formDataDetailDTO, paasFormDataEntityExt, formEntity, list, explainMap, data);
        handleSummarySpecialAttr(corpid, labelsList, businessType, data, dataId, paasFormDataEntityExt);
        return getTags(labelsList, corpid, businessType, dataId, userId);
    }

    @Override
    public String getTitle(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        List<FormTitlePoJo> formTitleList = getTitleList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        return TitleUtil.getWebTitle(formTitleList);
    }

    @Override
    public List<DetailTabPojo> handleDetailTab(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap, HandlerExplainVO handlerExplainVO, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        UserVO userVO = handelDetailPojo.getLoginUser();
        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        String corpid = paasFormDataEntityExt.getCorpid();
        String userId = userVO.getUserId();
        String platFormEnum = handlerExplainDTO.getPlatform();
        List<BusinessDetailTabEnum> tabEnumList = BusinessDetailTabEnum.getTabByBusinessTypeAndPermission(businessType, userVO.getPermSet(), platFormEnum);
        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formDataFormExplainHelper.getUserIdMap(Collections.singletonList(paasFormDataEntityExt.getDataId()),corpid,businessType,false,mainUserMap,coUserMap);

        // 当前数据的创建人、负责人、协同人、当前操作人
        handlerExplainDTO.setLoginUser(userVO);
        handlerExplainDTO.setUserId(userId);
        handlerExplainDTO.setOwnerId(mainUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCoUserId(coUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
        for (BusinessDetailTabEnum tabEnum : tabEnumList) {
            DetailTabPojo detailTabPojo = new DetailTabPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
            detailTabPojo.setAttr(detailTabPojo.getKey());
            if ( Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_COMMUNICATE_COMMENT)
                    || Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_COMMUNICATE_LIKE)){
                BusinessCommentEnum businessCommentEnum = BusinessCommentEnum.getByBusinessType(businessType);
                if (businessCommentEnum == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
                }
                Map<String, Object> commentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                commentMap.put("type", businessCommentEnum.getCode());
                commentMap.put("corpid",corpid);
                commentMap.put("refId",paasFormDataEntityExt.getDataId());
                commentMap.put("del",0);
                if (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_COMMUNICATE_COMMENT)){
                    Integer countNum = paasCommentModel.getEntitysCount(commentMap);
                    detailTabPojo.setCommentCount(countNum);
                }

                if (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_COMMUNICATE_LIKE)){
                    Integer likeNum = likeModel.getEntitysCount(commentMap);
                    detailTabPojo.setLikeCount(likeNum);
                }
            }
            tabPojoList.add(detailTabPojo);
        }
        handleTeamTab(tabPojoList, explainMap);
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        handlerExplainVO.setAppId(formEntity.getAppId());
        handlerExplainVO.setFormId(formEntity.getId());
        // 公共tab
        tabPojoList.addAll(linkListService.commonTab(corpid, userVO, handlerExplainVO, handlerExplainDTO, businessType, paasFormDataEntityExt.getDel(), linkList));
        // tab排序
        tabPojoList = detailTabConfigService.handleDetailTabSort(userVO.getUserId(), corpid, handlerExplainVO.getFormId(), businessType, tabPojoList);
        return tabPojoList;
    }


    @Override
    public void checkPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {
        if (loginUser.isMaxDataPermission()){
            return ;
        }
        Integer flowStatus = paasFormDataEntityExt.getFlowStatus();
        Long menuId = formEntity.getMenuId();
        Integer saasMark = formEntity.getSaasMark();
        Integer businessType = formEntity.getBusinessType();
        // 查看权限校验
        verifyQueryPermission(businessType, loginUser,saasMark ,menuId ,flowStatus);
        //校验消息页查看权限
        //boolean messageViewPermission = verifyMessageViewPermission(loginUser, paasFormDataEntityExt);
        //校验数据权限
        boolean dataPermission = verifyDataPermission(loginUser, paasFormDataEntityExt);
        if (!dataPermission){
            throw new XbbException(CustomerCommunicateErrorCodeEnum.API_ERROR_206013);
        }

    }

    /**
     * 校验数据权限(团队权限&共享权限)
     *
     * @param loginUser
     * @param paasFormDataEntityExt
     */
    private boolean verifyDataPermission(UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException{
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
        return commonPermissionHelp.checkViewPermission(verifyViewPermissionDTO);
    }

    /**
     * fix:53180 消息通知会把跟进记录消息推送给本不该看到这条数据的人(关联客户的非本团队的人),因此需要在详情页挡掉,不让这部分人看-逻辑By梦娜 代码By克辉
     *
     * @param loginUser
     * @param paasFormDataEntityExt
     */
    private boolean verifyMessageViewPermission(UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException{
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity);
        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, loginUser.getUserId(), loginUser.getCorpid(),BasicConstant.ZERO,false);
        CustomerEntityExt customerForm = null;
        ClueEntityExt clueForm = null;;
        boolean formShareTag;
        if (Objects.equals(paasFormDataEntityExt.getData().getInteger(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr()), XbbRefTypeEnum.CLUE.getCode())) {
            clueForm = clueModel.getByKey(Long.valueOf(paasFormDataEntityExt.getData().getString(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr())), paasFormDataEntityExt.getCorpid());
            //表单共享标识，true：共享  false：隔离
            formShareTag = userTeamHelp.getFormShareTag(paasFormDataEntityExt.getCorpid(), clueForm.getFormId(), XbbRefTypeEnum.CLUE.getCode());
        } else {
            if (Objects.nonNull(paasFormDataEntityExt.getData().getString(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr()))) {
                customerForm = customerModel.getByKey(Long.valueOf(paasFormDataEntityExt.getData().getString(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr())), paasFormDataEntityExt.getCorpid());
                formShareTag = userTeamHelp.getFormShareTag(paasFormDataEntityExt.getCorpid(), customerForm.getFormId(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            } else {
                //无客户签到的情况,直接赋值为true,不走进下面的if判断
                formShareTag = true;
            }
        }
        if (!(loginUser.isAdminOrBoss() || (Objects.nonNull(dataPermission) && Objects.equals(DataPermissionEnum.ALL.getCode(),dataPermission)) || formShareTag)) {
            if (userIdIn.contains(paasFormDataEntityExt.getCreatorId())) {
                return true;
            }
            Map<String,Object> param = new HashMap<>();
            param.put("corpid", paasFormDataEntityExt.getCorpid());
            if (Objects.nonNull(customerForm)) {
                param.put("dataId", customerForm.getId());
            } else {
                param.put("dataId", clueForm.getId());
            }
            param.put("userId", loginUser.getUserId());
            param.put("del", BasicConstant.ZERO);
            Integer count = customerUserModel.getEntitysCount(param);
            return count != 0;
        }
        return true;
    }


    @Override
    public JSONObject analysisData(PaasFormDataEntityExt paasFormDataEntityExt, HandlerExplainDTO handlerExplainDTO, HandlerExplainVO handlerExplainVO) throws XbbException {
        Long formId = paasFormDataEntityExt.getFormId();
        List<FieldAttrEntity> list = handlerExplainVO.getHeadList();
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(list.size());
        list.forEach(item->explainMap.put(item.getAttr(), item));

        ParseSingleRowDataVO parseSingleRowDataVO = commonAnalysisData(paasFormDataEntityExt, handlerExplainDTO, handlerExplainVO, list, explainMap);
        JSONObject data = parseSingleRowDataVO.getResult();

        handleDetailSpecialField(paasFormDataEntityExt, data, explainMap, handlerExplainDTO);
        SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
        BeanUtil.copyProperties(handlerExplainDTO, saasAnalysisDataDTO);
        saasAnalysisDataDTO.setFormId(formId);
        customerCommunicateModel.formatData(saasAnalysisDataDTO, data);
        //处理千分位
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        formDataGetVO.setData(data);
        formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO, list, false);
        return data;
    }
}
